<template>
  <div class="appointment-management">
    <div class="page-header">
      <h2>预约管理</h2>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="服务">
          <el-select v-model="searchForm.serviceId" placeholder="请选择服务" clearable>
            <el-option
              v-for="item in serviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预约列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="appointmentList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="预约ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="serviceName" label="预约服务" width="150" />
        <el-table-column prop="petName" label="宠物名称" width="120" />
        <el-table-column label="预约时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="预约状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.status === 'PENDING'"
              @click="handleConfirm(scope.row)">确认</el-button>
            <el-button
              size="mini"
              type="warning"
              v-if="scope.row.status === 'PENDING' || scope.row.status === 'CONFIRMED'"
              @click="handleComplete(scope.row)">完成</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="scope.row.status === 'PENDING' || scope.row.status === 'CONFIRMED'"
              @click="handleCancel(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog title="预约详情" :visible.sync="detailDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="预约ID">{{ currentAppointment.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentAppointment.username }}</el-descriptions-item>
        <el-descriptions-item label="服务名称">{{ currentAppointment.serviceName }}</el-descriptions-item>
        <el-descriptions-item label="服务价格">¥{{ currentAppointment.servicePrice }}</el-descriptions-item>
        <el-descriptions-item label="宠物名称">{{ currentAppointment.petName }}</el-descriptions-item>
        <el-descriptions-item label="宠物类型">{{ currentAppointment.petType }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ formatDateTime(currentAppointment.appointmentTime) }}</el-descriptions-item>
        <el-descriptions-item label="预约状态">
          <el-tag :type="getStatusType(currentAppointment.status)">
            {{ getStatusText(currentAppointment.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentAppointment.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentAppointment.updatedTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentAppointment.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          type="success" 
          v-if="currentAppointment.status === 'PENDING'"
          @click="handleConfirm(currentAppointment)">确认预约</el-button>
        <el-button 
          type="warning" 
          v-if="currentAppointment.status === 'PENDING' || currentAppointment.status === 'CONFIRMED'"
          @click="handleComplete(currentAppointment)">完成预约</el-button>
        <el-button 
          type="danger" 
          v-if="currentAppointment.status === 'PENDING' || currentAppointment.status === 'CONFIRMED'"
          @click="handleCancel(currentAppointment)">取消预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAppointmentList, updateAppointmentStatus } from '@/api/admin'
import { getServiceList } from '@/api/admin'
import { formatDateTime } from '@/utils/date'

export default {
  name: 'AppointmentManagement',
  
  data() {
    return {
      loading: false,
      appointmentList: [],
      serviceOptions: [],
      searchForm: {
        username: '',
        serviceId: '',
        status: '',
        dateRange: []
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      detailDialogVisible: false,
      currentAppointment: {},
      statusOptions: [
        { value: 'PENDING', label: '待确认' },
        { value: 'CONFIRMED', label: '已确认' },
        { value: 'COMPLETED', label: '已完成' },
        { value: 'CANCELLED', label: '已取消' }
      ]
    }
  },

  created() {
    this.fetchServiceOptions()
    this.fetchData()
  },

  methods: {
    formatDateTime,

    // 获取服务选项
    async fetchServiceOptions() {
      try {
        const { data } = await getServiceList({ 
          pageNum: 1, 
          pageSize: 100,
          name: '',
          category: '',
          status: ''
        })
        this.serviceOptions = data.list || []
      } catch (error) {
        console.error('获取服务列表失败:', error)
      }
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        'PENDING': 'warning',
        'CONFIRMED': 'primary',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待确认',
        'CONFIRMED': '已确认',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },

    // 获取预约列表数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.searchForm,
          startDate: this.searchForm.dateRange?.[0],
          endDate: this.searchForm.dateRange?.[1]
        }
        delete params.dateRange
        const { data } = await getAppointmentList(params)
        this.appointmentList = data.list || []
        this.page.total = data.total || 0
      } catch (error) {
        console.error('获取预约列表失败:', error)
        this.$message.error('获取预约列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.page.pageNum = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        serviceId: '',
        status: '',
        dateRange: []
      }
      this.handleSearch()
    },

    // 切换页码大小
    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },

    // 切换页码
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchData()
    },

    // 查看详情
    handleDetail(row) {
      this.currentAppointment = { ...row }
      this.detailDialogVisible = true
    },

    // 确认预约
    async handleConfirm(row) {
      try {
        await this.$confirm('确认该预约申请吗？', '提示', {
          type: 'warning'
        })
        await updateAppointmentStatus(row.id, 'CONFIRMED')
        this.$message.success('预约已确认')
        this.fetchData()
        if (this.detailDialogVisible) {
          this.detailDialogVisible = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('确认预约失败:', error)
          this.$message.error('确认预约失败')
        }
      }
    },

    // 完成预约
    async handleComplete(row) {
      try {
        await this.$confirm('确认将该预约标记为已完成吗？', '提示', {
          type: 'warning'
        })
        await updateAppointmentStatus(row.id, 'COMPLETED')
        this.$message.success('预约已完成')
        this.fetchData()
        if (this.detailDialogVisible) {
          this.detailDialogVisible = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('完成预约失败:', error)
          this.$message.error('完成预约失败')
        }
      }
    },

    // 取消预约
    async handleCancel(row) {
      try {
        await this.$confirm('确认取消该预约吗？', '提示', {
          type: 'warning'
        })
        await updateAppointmentStatus(row.id, 'CANCELLED')
        this.$message.success('预约已取消')
        this.fetchData()
        if (this.detailDialogVisible) {
          this.detailDialogVisible = false
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消预约失败:', error)
          this.$message.error('取消预约失败')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.appointment-management {
  padding: 20px;

  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .list-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style> 